﻿#pragma strict
@script AddComponentMenu("Level4/Transform/MoveCharacterMotor")
////////////////////////////////////////////////////////////////////////////////////
/// 没有任何状态的角色移动器.无动画控制.
/// 分世界方向,本地方向.moveType来控制.
////////////////////////////////////////////////////////////////////////////////////
class CharacterMoveMotor extends MonoBehaviour{
	//移动类型
	enum MoveType{world,local};
	var moveType:MoveType;
	//是否可
	var canJump:boolean;
	var canMove:boolean = true;
	//下降的速度(m/s)
	var gravity:float = 20; 
	// 角色的移动速度 
	var moveSpeed:float = 4;
	// 角色跳跃的高度(m).
	var jumpHeight:float = 4;
	//脚步音效
	var moveSound:AudioClip;
	//脚步 时间间隔
	var moveSoundDeltaTime:float = .4;
	//移动的方向.
	var moveDir:Vector3;

	var isTest:boolean;

	var characterController:CharacterController;

	private var tr:Transform;
	private var lastMoveSoundTime:float;

	function Awake () {
		tr = transform;
		characterController = GetComponent.<CharacterController>();
		if(! characterController)
			characterController = gameObject.AddComponent.<CharacterController>();
	}

	function Update () {
		if(isTest){
			StartMove();
		}
	}

	function StartMove(){
		var h:float = Input.GetAxis("Horizontal");
		var v:float = Input.GetAxis("Vertical");
		var isJump:boolean = canJump && Input.GetButtonDown("Jump");
		
		Move(h,v,isJump);	
	}

	function Move(h:float,v:float,isJump:boolean){
		if(characterController.isGrounded){
			moveDir = Vector3(h,0,v);
			moveDir = Vector3.ClampMagnitude(moveDir,1);
			moveDir *= moveSpeed;
			if(moveType == MoveType.local){
				moveDir = tr.TransformDirection(moveDir);
			}
			if(isJump){
				moveDir.y = jumpHeight;
			}
			PlayMoveSound(h,v);
		}
		moveDir.y -= gravity * Time.deltaTime;
		characterController.Move(moveDir * Time.deltaTime);
	}
	
	function PlayMoveSound(h:float,v:float){
		if(moveSound){
			if( h != 0 || v != 0){
				if(Time.time > lastMoveSoundTime + moveSoundDeltaTime){
					AudioHelper.MakeSureAudioSource(gameObject);
					audio.PlayOneShot(moveSound);
					lastMoveSoundTime = Time.time;
				}
			}
		}
	}
	
}